<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2024-9-28 10:55:00
// +----------------------------------------------------------------------

namespace buwang\middleware;

use buwang\interfaces\MiddlewareInterface;
use app\Request;
use think\Route;

class CheckAddonsRoute implements MiddlewareInterface
{
    public function handle(Request $request, \Closure $next)
    {
        $pathInfo = $request->pathinfo();
        // 判断是否是插件路由
        if (str_starts_with($pathInfo, 'addons/')) {
            // 提取插件信息
            $segments = array_slice(explode('/', $pathInfo), 1); // 去掉 addons 后的数组
            [$addon, $controller, $action] = array_pad($segments, 3, '');

            file_put_contents('addon_access002.log', sprintf(
                "[%s] %s => %s %s %s\n",
                date('Y-m-d H:i:s'),
                $request->ip(),
                $addon,
                $controller,
                $action
            ), FILE_APPEND);


            $service = new \buwang\service\AddonsService(app());
            // 注册插件路由
            $service->triggerRegisterRoutes(function (Route $route) use ($addon, $controller, $action) {
                $execute = '\\think\\addons\\Route::execute';
                $route->rule("addons/{$addon}/{$controller}/{$action}", $execute)
                    ->name("addons/{$addon}/{$controller}/{$action}")
                    ->completeMatch(true)
                    ->append([
                        'addon' => $addon,
                        'controller' => $controller,
                        'action' => $action
                    ])->middleware(\think\addons\middleware\Addons::class);
            });

        }

        return $next($request);
    }


}